import { cloneObj } from '@/utils/data'
function keyCollect(data, pk) {
  let res = []

  data.forEach(item => {
    if (item[pk]) {
      res.push(item[pk])
    }
  })
  return res
}

export default {
  data() {
    return {
      api: () => {
        console.log('请配置api')
      },
      saveApi: () => {
        console.log('请配置saveApi')
      },
      loading: false,
      epData: [],
      epPager: {
        limit: 10,
        offset: 1
      },
      epDataTotal: 0,
      searchForm: {},
      settings: {
        rowsName: 'rows',
        totalName: 'total',
        pk: 'id',
        pagerKey: 'epPager', // data 中 pager 的 key 值
        pagerLimitName: 'limit', // 指定新namede的话 pagerkey也最好换一个
        pagerOffsetName: 'offset' //  指定新namede的话 pagerkey也最好换一个
      }
    }
  },
  mounted() {
    this.refresh(true)
  },
  methods: {
    refresh(init = false) {
      let { settings } = this
      if (init) {
        this[settings.pagerKey][settings.pagerOffsetName] = 1
      }
      // 校验
      let p = Promise.resolve()
      if (this.$refs.searchForm) {
        p = new Promise((resolve, reject) => {
          this.$refs.searchForm.validate(valid => {
            if (valid) {
              resolve()
            } else {
              reject()
            }
          })
        })
      }
      return p
        .then(_ => {
          let req = cloneObj(Object.assign({}, this[settings.pagerKey], this.searchForm))
          this.loading = true
          return this.api(req).then(res => {
            let { data } = res
            let rows = data[this.settings.rowsName]
            let total = data[this.settings.totalName]
            this.epDataTotal = total
            this.epData = rows
            this.loading = false
          })
        })
        .catch(e => {
          console.log(e, '请求出错')
          this.loading = false
        })
    },
    handlePageChange(val) {
      let { settings } = this
      this[settings.pagerKey][settings.pagerOffsetName] = val
      this.refresh()
    },
    sizeChange(val) {
      if (val) {
        let { settings } = this
        this[settings.pagerKey][settings.pagerLimitName] = val
        this.refresh(true)
      }
    },
    reset() {
      this.$refs.searchForm.reset()
    },
    // 重置可编辑表格
    resetEditTable() {
      this.$refs.searchTable.reset()
    },
    // 添加新数据
    addEditTable() {
      this.$refs.searchTable.addRow()
    },
    // 删除当前选中行
    deleteEditTableRow() {
      this.$refs.searchTable.deleteSelectRow()
    },
    // 保存
    saveEditTable() {
      let reqData = {}
      let p = new Promise((resolve, reject) => {
        this.$refs.searchTable.getSaveData(data => {
          this.loading = true
          for (let item in data) {
            if (Object.hasOwnProperty.call(data, item)) {
              if (item === 'delete') {
                try {
                  reqData[item] = keyCollect(data[item], this.settings.pk)
                } catch (e) {
                  reject()
                  console.log(e)
                  this.$pop({
                    type: 'danger',
                    message: '配置项缺失或配置错误的主键！',
                    hasClose: true
                  })
                  return
                }
              } else {
                reqData[item] = data[item]
              }
            }
          }
          resolve()
        })
      })
      return p.then(_ => {
        return this.saveApi(reqData)
          .then(res => {
            this.$success('修改成功！')
            this.refresh()
          })
          .catch(e => {
            console.error(e)
            this.loading = false
          })
      })
    }
  }
}
